<?php
declare(strict_types=1);

namespace Modules\Web\Service;

use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Service\PayRefundService;
use Modules\Admin\Service\OrderRepairstoreService;

class RepairOrderService extends BaseService
{
    /**
     * 服务商品订单列表
     * yang 2019 11 01
     */
    public function get_repair_order_list(array $arr_search)
    {
        try {
            $shop_id = get_web_shop_id();//门店id

            $search = array();
            if ($arr_search['status'] == '1') {//待支付
                $search['pay_status'] = '0';
                $search['status'] = '0';
            } elseif ($arr_search['status'] == '2') {//待待检修
                $search['pay_status'] = '1';
                $search['status'] = '0';
            } elseif ($arr_search['status'] == '3') {//已完成
                $search['pay_status'] = '1';
                $search['status'] = '3';
            } elseif ($arr_search['status'] == '4') {//申请退款
                $search['pay_status'] = '2';
                $search['status'] = '0';
            }
            if ($arr_search['date_time']) {//时间
                $search['date_time'] = $arr_search['date_time'];
            }
            if ($arr_search['user_id']) {
                $search['user_id'] = $arr_search['user_id'];
            }

            $arr_option['where'] = ['shop_id' => $shop_id];//商户id
            $arr_option['with'] = ['shop', 'repair_goods_pic'];
            $data = OrderRepairstoreRepository::api_get_list($arr_option, (array)$search);
            $arr_list = list_page_data($data);

            $result = array();
            foreach ($arr_list['data'] as $key => $item) {
                if ($item['is_online_pay'] == 1 && $item['status'] == 0) {
                    $order_status = '待处理';
                } else {
                    $order_status = OrderRepairstoreRepository::orderStatus($item['status'], $item['pay_status']);
                }
                if ($item['order_type'] == 1) {
                    $pic_url = $item['repair_goods_pic']['picurl']['full_src'];
                } else {
                    $pic_url = $item['shop']['logo']['full_src'];
                }

                $result[] = array(
                    "id" => $item['id'],
                    "order_number" => $item['order_number'],
                    "order_type" => $item['order_type'],
                    "order_price" => $item['order_price'],
                    "created_at" => $item['created_at'],
                    "goods_id" => $item['repairstore_goods_id'],
                    "goods_name" => $item['goods_name'],
                    "goods_pic" => $pic_url,
                    "pay_type" => $item['pay_type'],
                    "is_online_pay" => $item['is_online_pay'],
                    "status" => $item['status'],
                    "pay_status" => $item['pay_status'],
                    "order_status" => $order_status
                );
            }

            return hello_success('获取成功', ['list' => $result, 'page' => $arr_list['page_data']]);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 服务商品订单详情
     * yang 2019 11 01
     */
    public function get_repair_order_info(int $oid)
    {
        try {
            if (empty($oid)) {
                return hello_error('订单id不能为空');
            }
            //获取用户订单信息
            $map = ['id' => $oid];
            $arr_option['with'] = ['user', 'maintain_goods', 'repair_goods_pic'];

            $order_obj = OrderRepairstoreRepository::get_one_by_where((array)$map, $arr_option);

            if ($order_obj->first()) {
                $order = $order_obj->toarray();
                if ($order['order_type'] == 2 && !empty($order['maintain_goods'])) {//保养订单
                    foreach ($order['maintain_goods'] as $ky => $val) {
                        $maintain_goods[] = [
                            'goods_id' => $val['goods_id'],
                            'goods_name' => $val['get_goods']['name'],
                            'goods_num' => $val['goods_num'],
                            'goods_price' => $val['goods_price'],
                            'goods_pic' => $val['get_product']['pic']['full_src'],
                            'product_specs' => $val['get_product']['specs']['name'],
                        ];
                    }
                } else {//服务订单
                    $repair_goods = [
                        'goods_id' => $order['repairstore_goods_id'],
                        'goods_pic' => $order['repair_goods_pic']['picurl']['full_src'],
                        'goods_num' => $order['goods_num'],
                        'goods_price' => $order['order_price'],
                    ];
                }

                if ($order['is_online_pay'] == 1 && $order['status'] == 0) {
                    $order['order_status'] = '待处理';
                } else {
                    $order['order_status'] = OrderRepairstoreRepository::orderStatus($order['status'], $order['pay_status']);
                }

                $order['maintain_goods'] = $maintain_goods ?? null;//保养订单中的商品数组
                $order['goods'] = $repair_goods ?? null;//服务订单商品信息;
                $order['refund_price'] = $order['pay_price'];

                return hello_success('获取成功', $order);
            }

            return hello_error('订单不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 订单状态处理
     * 2019 11 01
     */
    public function chang_repair_status(array $arrInput)
    {
        try {
            if (empty($arrInput['id'])) {
                return hello_error('订单id不能为空');
            }
            $arr_input['id'] = $arrInput['id'];
            if ($arrInput['status'] == '1') {  //确认检修

                $arr_option['field'] = ['is_scanning_code', 'is_online_pay'];
                $info = OrderRepairstoreRepository::get_one((int)$arr_input['id'], $arr_option);
                if ($info['is_scanning_code'] != 1) {
                    return hello_error('请重新扫码确认！');
                }
                if ($info['is_online_pay'] == 1) {
                    $arr_input['pay_status'] = 1;
                    $arr_input['pay_time'] = date('Y-m-d H:i:s');
                }
                $arr_input['status'] = 1;
                $arr_input['checked_at'] = date('Y-m-d H:i:s');//检修时间
                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 60,
                    'title' => '处理通知',
                    'content' => '商家已确认处理'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif ($arrInput['status'] == '2') {  //取消订单
                if (empty($arrInput['cancel_reason'])) {
                    return hello_error('取消订单原因不能为空');
                }
                $arr_input['status'] = 2;
                $arr_input['cancel_reason'] = $arrInput['cancel_reason'];

                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 37,
                    'title' => '取消订单通知',
                    'content' => '已被商家取消'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif ($arrInput['status'] == '3') {  //关闭订单
                $arr_input['status'] = 4;
            } else {
                return hello_error('处理状态有误');
            }

            OrderRepairstoreRepository::edit_one($arr_input);

            return hello_success('操作成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 退款处理
     * 2019 11 01
     */
    public function refund_repair_order(array $arrInput)
    {
        try {
            if (empty($arrInput['id'])) {
                return hello_error('订单id不能为空');
            }
            $arr_input['id'] = $arrInput['id'];

            if ($arrInput['type'] == '1') {//确认退款
                $order = OrderRepairstoreRepository::get_one((int)$arrInput['id']);

                if ($order->first()) {
                    $info = $order->toArray();
                    $s_order_sn = $info['order_number'];//订单编号
                    $s_refund_sn = $info['order_number'];//退单编号

                    //退款处理
                    return PayRefundService::api_online_pay_refund($s_order_sn, $s_refund_sn);
                }

                return hello_error('订单不存在');
            } elseif ($arrInput['type'] == '2') {  //拒绝退款
                $arr_input['pay_status'] = 4;
                OrderRepairstoreRepository::edit_one($arr_input);

                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 33,
                    'title' => '拒绝退款通知',
                    'content' => '商家已拒绝退款'
                ];
                predis_notice_queue_in($dataNotice);

            } else {
                return hello_error('处理状态有误');
            }

            return hello_success('操作成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商户端扫码确认可以完成订单
     * @param $arr_input
     * @return array
     */
    public function scanning_code($arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            $shop_id = get_web_shop_id();//门店id
            $map = [
                'id' => intval($arr_input['order_id']),
                'shop_id' => $shop_id,
                'status' => 0
            ];
            $up_data = ['is_scanning_code' => 1];

            $res = OrderRepairstoreRepository::edit_pay_status($map, $up_data);

            if ($res) {
                return hello_success('可以处理订单');
            }
            return hello_error('请重新扫码确认订单（是否为待处理，是否为该门店订单）');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }
}